package com.cpvideo

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
//import com.blen.videolib.NativeLib
import com.cpvideo.activities.VideoActivity
import com.blen.videolib.VideoEditActivity
import com.blen.videolib.VideoRecorderActivity
import com.blen.videolib.VideoSDK
import com.blen.videolib.util.FFUtils
import com.blen.videolib.util.StringUtils
import icangyu.base.utils.ExecutorPool
import icangyu.base.utils.FileUtils
import icangyu.base.utils.ImageLoader
import icangyu.base.utils.LogUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener{

    private var videoPath:String? = null
    private var cover:String?=null
    val handler  = Handler({
            msg->
        false
    })

    private var cmd: Array<String?>?=null
//    private var cmd:Array<String>? = null

    private var des:String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//        checkPermission(arrayOf(
//            Manifest.permission.CAMERA,
//            Manifest.permission.RECORD_AUDIO,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
//        ),100)

        //arm64-v8a, armeabi-v7a,armeabi
        if(android.os.Build.VERSION.SDK_INT<21) {
            LogUtils.b(android.os.Build.CPU_ABI)
            LogUtils.b(android.os.Build.CPU_ABI2)
        }else {
            var a = Build.SUPPORTED_ABIS;
            for(b in a){
                LogUtils.b(b)
            }
        }
        VideoSDK.initSDK( FileUtils.getCachePath(this).toString(), FileUtils.getJadeDCIM().toString(),true,ExecutorPool.getInstance());
    }


    override fun onResume() {
        super.onResume()
        handler.sendEmptyMessage(1)
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        LogUtils.l("blen",manufacturer,model)
        LogUtils.l("blen",Build.MANUFACTURER,Build.BOARD,Build.MODEL,Build.DEVICE,Build.BRAND,Build.ID,Build.VERSION.SDK_INT)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.imgPlay->{
                if(!videoPath.isNullOrEmpty()) {
                    val inten = Intent(this, VideoActivity::class.java)
                    inten.putExtra("url", videoPath)
                    startActivity(inten)
                }
            }
            R.id.btShot->{
                if(!VideoSDK.initSDK( FileUtils.getJadeCache().toString(), FileUtils.getJadeDCIM().toString(),true,ExecutorPool.getInstance())){
                    Toast.makeText(this, "初始化失败",Toast.LENGTH_SHORT).show();
                    return;
                }
                val intent = Intent(this, VideoRecorderActivity::class.java)
//                val intent = Intent(this,MediaRecorderActivity::class.java)
//                registerForActivityResult()
                startActivity(intent)
            }
            R.id.btSelect->{
                selectVideo()
            }
            R.id.tvJx->{
//                LogUtils.d("fromNative",NativeLib().stringFromJNI());
//                try {
//                    FFUtils.runSync(cmd){
//                        code->
//                        ImageLoader.showOrFile(this,imgPlay,des);
//                    }
////                    FFUtils.run(etCmd.text.toString())
//                }catch(e:Throwable){
//                    e.printStackTrace()
//                }
            }
            R.id.tvCB->{
                LogUtils.b("tvCB clicked")
                if(!TextUtils.isEmpty(videoPath)){
                    //生成图片
//                    val cmd = etCmd.text.toString()
                    LogUtils.b(getCMD())
                    LogUtils.b("ffpegCode:"+ FFUtils.run(cmd))
                    ImageLoader.showOrFile(this,imgPlay,des);
                }
            }
            R.id.tvFlib->{
                val intent = Intent(this, VideoEditActivity::class.java)
                intent.putExtra("path", videoPath)
                Log.d("blensmile", "path is: $videoPath")
                startActivityForResult(intent, 100)
                LogUtils.b("flip clicked")
                if(!TextUtils.isEmpty(videoPath)){
                    //生成图片
//                    val cmd = etCmd.text.toString()
//                    LogUtils.b(cmd)
//                    LogUtils.b("ffpegCode:"+ FFmpeg.getsInstance().executeCmd(cmd))
//                    ImageLoader.showOrFile(this,imgPlay,des,R.drawable.def_cover);

                }


            }
            R.id.tvRun->{
//                etCmd.setText( getCMD())
                val cmd = etCmd.text.toString()
                if(cmd.isNotEmpty()){
                    FFUtils.run(cmd)
                }
            }
        }
    }

    fun getCMD():String {
        val ss = " -ss 1 "
        des = FileUtils.getJadeDCIM().append("/").append(System.currentTimeMillis()).append(".jpg").toString();
        cmd = arrayOf("ffmpeg",
            "-ss",
            "1",
            "-i",
            videoPath,
            "-vframes",
            "1",
            des
            )
//        return getcmdstring()
        return StringUtils.concat(cmd," ")
    }
//    fun getCaptureThumbnailsCMD(videoPath: String, outputPath: String, ss: String?): Boolean {
//        var ss = ss
//        if (ss == null)
//            ss = ""
//        else
//            ss = " -ss $ss"
//        return FFmpegBridge.jxFFmpegCMDRun(
//            String.format(
//                "ffmpeg  -i  %s %s -vframes 1  %s ",
//                videoPath,
//                ss,
//                outputPath
//            )
//        ) == 0
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK && requestCode == 100 && data!=null){
//            intent.putExtra("video", data.getStringExtra("videoPath"))
//            intent.putExtra("cover", data.getStringExtra("cover"))
            videoPath = data.getStringExtra("video")
            cover = data.getStringExtra("cover")
            if(!cover.isNullOrEmpty()){
                //显示图片
                ImageLoader.showOrFile(this,imgPlay,cover);
            }
            tvInfo.setText(videoPath)
        }else if(resultCode == Activity.RESULT_OK && requestCode == 1001){
            val uri = data?.getData()
            videoPath = uri?.toString()
            if(videoPath!=null) {
                if (videoPath!!.startsWith("content://")) {
                    videoPath =
                           FileUtils.getPathByUri4kitkat(
                                this,
                                uri
                            )
                } else if (videoPath!!.startsWith("file://")) {
                    videoPath = videoPath!!.substring(7)
                }
                tvInfo.setText(videoPath)
            }
        }
    }

    fun selectVideo(){
        val intent = Intent()
        intent.type = "video/*" //选择视频 （mp4 3gp 是android支持的视频格式）
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, 1001)
    }

}
